package org.zfes.snowy.base.web.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.zfes.snowy.base.handlers.SimpleRepeatTokenHandler;
import org.zfes.snowy.core.util.ZStrUtil;

public class RepeatSubmitInterceptor extends HandlerInterceptorAdapter{

	private static final String repeatTokenName="_repeattoken_";
	
	private SimpleRepeatTokenHandler simpleRepeatTokenHandler;
	
	@Override
	public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {
		super.afterCompletion(request, response, handler, ex);
		HttpSession session=request.getSession(false);
		if(session!=null){
			session.removeAttribute(repeatTokenName);
		}
	}

	@Override
	public void postHandle(HttpServletRequest request,	HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
		HttpSession session=request.getSession(false);
		if(session!=null){
			session.removeAttribute(repeatTokenName);
		}
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		 if (handler instanceof HandlerMethod) {
	            HttpSession session=request.getSession(false);
            	if(session==null){
            		return true;
            	}
            	String seesionId=session.getId();
            	String uri=request.getRequestURI();
            	String qstr=request.getQueryString();
            	String repeatToken=seesionId+uri+qstr;
            	
            	String repeatTokenInsession=(String) session.getAttribute(repeatTokenName);
            	if(ZStrUtil.hasNoText(repeatTokenInsession)){
            		session.setAttribute(repeatTokenName, repeatToken);
            		return true;
            	}else{
            		simpleRepeatTokenHandler.onRepeatSubmit(request, response);
            		return false;
            	}
	        } else {
	            return super.preHandle(request, response, handler);
	        }
		
	}

	public SimpleRepeatTokenHandler getSimpleRepeatTokenHandler() {
		return simpleRepeatTokenHandler;
	}

	public void setSimpleRepeatTokenHandler(SimpleRepeatTokenHandler simpleRepeatTokenHandler) {
		this.simpleRepeatTokenHandler = simpleRepeatTokenHandler;
	}

}
